const winston = require('winston');
var merchantService = require('../service/merchant.service');
var client = require('./jms.client');

client.connect(connectedCallback,errCallback);
function connectedCallback(sid){
    client.subscribe(client.destination,function(message,headers){
        winston.info('jms receive a message:['+message+']');
        var pro = JSON.parse(message);
        if(pro.result){
            var merchant = {
                _id:pro.data._id,
                mName:pro.data.account,
                shopName:pro.data.name,
                address:pro.data.address,
                imgHead:pro.data.imgHead,
                imgCard:pro.data.imgCard,
                ban:false,
                rejectContent:'',
                status:0,
                createTime:new Date()
            }

            //add or update jms data to db
            merchantService.findMerchantById(merchant._id,function (err,doc) {
                if(err){
                    winston.error('jms get merchant fail'+err.message);
                }else {
                    if(doc){
                        merchantService.updateMerchent(merchant,function (err,result) {
                            if(err){
                                winston.error('jms update merchant data fail');
                            }else {
                                winston.info('jms update merchant data success');
                            }
                        });
                    }else {
                        merchantService.addMerchant(merchant,function (err,result) {
                            if(err){
                                winston.error('jms add merchant data fail');
                            }else {
                                winston.info('jms add merchant data success');
                            }
                        });
                    }
                }
            });
        }else {
            winston.error('jms data is bad')
        }
    });
}
function errCallback(){
    console.error('jms connected error');
    client.disconnect();
}